package parsing;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;

import java.util.StringTokenizer;


public class Reader {
	
	public void readFileWriteToFile(String filePathToRead, String filePathToWrite){
		// STA AKO NEMA FAJLOVA ILI NE MOZES DA PROCITAS, KREIRAS NOVI FAJL?
		if((filePathToRead != null)&&(filePathToWrite != null)){
			File fileToRead = new File(filePathToRead);
			File fileToWrite = new File(filePathToWrite);
			if(fileToRead.canRead()&& fileToWrite.canWrite()){
				BufferedReader in = null;
				BufferedWriter out = null;
				try {
					in = new BufferedReader(new FileReader(fileToRead));
					out = new BufferedWriter(new FileWriter(fileToWrite));
	        
					HashMap<String, Integer> mapOfKeys = new HashMap<String, Integer>();
					HashMap<String, Integer> mapOfValues = new HashMap<String, Integer>();
	        
					String line = in.readLine();
					while (line != null){
						if (line.contains("=")){ // jump over bad line. bad line is a string that does not contain "=".
							StringTokenizer st = new StringTokenizer(line, "=");
	        		
	        	
							while(st.hasMoreTokens()) {
								String key = st.nextToken(); 
								String value = st.nextToken();
	        		
								countOccurrence(mapOfKeys, key);
								countOccurrence(mapOfValues, value);
							}
						}
						line = in.readLine();
					}
	        
					writeOut(out, mapOfKeys);
					writeOut(out,mapOfValues);
	        	        
				} catch (IOException e) {
					e.printStackTrace();
				}finally{
					closeReader(in);
					closeWriter(out);
				}
			}
		}
	}
	

	public void closeWriter(BufferedWriter out) {
		try {
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void closeReader(BufferedReader in) {
		try {
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void writeOut(BufferedWriter out, HashMap<String, Integer> mapOfKeys)
			throws IOException {
		Iterator<String> iterator = mapOfKeys.keySet().iterator();
		while(iterator.hasNext()){
			String key = iterator.next().toString();
			String value = mapOfKeys.get(key).toString();
			
			out.write(key + "-" + value + "\n");
		}
	}
	
	public void countOccurrence(HashMap<String, Integer> mapOfKeys, String key) {
		if (!mapOfKeys.containsKey(key)){
			mapOfKeys.put(key, 1);
		}else{
			Integer numberOfKeys; 
			numberOfKeys = mapOfKeys.get(key);
			mapOfKeys.put(key, numberOfKeys+1);
		}
	}
	
	public static void main(String args[]){
		Reader r = new Reader();
		r.readFileWriteToFile("C:/Documents and Settings/Snezana/Desktop/text.txt","C:/Documents and Settings/Snezana/Desktop/result.txt");
	}
}

